# -*- coding: utf-8 -*-
import json
import traceback

import requests
import time


def post(url, data, token, head_args=None):
    headers = {'Content-Type': 'application/json'}
    if token:
        headers['X-TOKEN'] = token
    if head_args:
        for key in head_args.keys():
            headers[key] = head_args.get(key)
    body = json.dumps(data)

    session = requests.session()
    try:
        print("发出请求：\n    url=%s, \n    token=%s \n    data=%s" % (url, token, data))
        start_time = time.time()  # 记录开始时间
        ret = session.post(url=url, data=body, headers=headers, timeout=10)
        end_time = time.time()  # 记录程序结束时间
        total_time = end_time - start_time  # 计算程序执行耗时

        result = ret.json()
        status = result["status"]
        msg = result["message"]

        if ret.status_code != 200:
            raise Exception("网络调用异常，status_code：" + str(ret.status_code)
                            + ", status: " + str(status) + ", message: " + msg)

        print("接收到答复信息，[耗时:%.5f秒] status：%s，message：%s \n %s"
              % (total_time, status, msg, result))
        return result
    except Exception as e:
        print("发生异常：", e)
        print(traceback.format_exc())
        return None
